#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证相关API路由
"""

from flask import Blueprint, request, jsonify
from models.user import User
from models.admin import Admin
from database import db
import jwt
import requests
from datetime import datetime, timedelta
import os

auth_bp = Blueprint('auth', __name__)

# 微信小程序配置
WECHAT_APPID = 'your_wechat_appid'
WECHAT_SECRET = 'your_wechat_secret'

@auth_bp.route('/wechat/login', methods=['POST'])
def wechat_login():
    """微信小程序登录"""
    try:
        data = request.get_json()
        code = data.get('code')
        user_info = data.get('userInfo', {})
        
        if not code:
            return jsonify({'success': False, 'message': '缺少授权码'}), 400
        
        # 调用微信API获取session_key和openid
        wx_url = f'https://api.weixin.qq.com/sns/jscode2session'
        wx_params = {
            'appid': WECHAT_APPID,
            'secret': WECHAT_SECRET,
            'js_code': code,
            'grant_type': 'authorization_code'
        }
        
        # 这里为了演示，使用模拟数据
        # 实际项目中需要真实调用微信API
        # response = requests.get(wx_url, params=wx_params)
        # wx_data = response.json()
        
        # 模拟微信返回数据
        wx_data = {
            'openid': f'mock_openid_{code}',
            'session_key': 'mock_session_key',
            'unionid': f'mock_unionid_{code}'
        }
        
        if 'errcode' in wx_data:
            return jsonify({'success': False, 'message': '微信授权失败'}), 400
        
        openid = wx_data.get('openid')
        unionid = wx_data.get('unionid')
        
        # 查找或创建用户
        user = User.query.filter_by(openid=openid).first()
        if not user:
            user = User(
                openid=openid,
                unionid=unionid,
                nickname=user_info.get('nickName'),
                avatar_url=user_info.get('avatarUrl'),
                gender=user_info.get('gender', 0),
                city=user_info.get('city'),
                province=user_info.get('province'),
                country=user_info.get('country')
            )
            db.session.add(user)
        else:
            # 更新用户信息
            if user_info.get('nickName'):
                user.nickname = user_info.get('nickName')
            if user_info.get('avatarUrl'):
                user.avatar_url = user_info.get('avatarUrl')
            user.last_login_at = datetime.now()
        
        db.session.commit()
        
        # 生成JWT令牌
        token_payload = {
            'user_id': user.id,
            'openid': user.openid,
            'exp': datetime.utcnow() + timedelta(days=7)
        }
        token = jwt.encode(token_payload, 'billiard-jwt-secret', algorithm='HS256')
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'data': {
                'token': token,
                'user': user.to_dict()
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'登录失败: {str(e)}'}), 500

@auth_bp.route('/admin/login', methods=['POST'])
def admin_login():
    """管理员登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
        
        # 查找管理员
        admin = Admin.query.filter_by(username=username).first()
        if not admin or not admin.verify_password(password):
            return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
        
        if admin.status != 1:
            return jsonify({'success': False, 'message': '账户已被禁用'}), 403
        
        # 更新登录信息
        admin.last_login_at = datetime.now()
        admin.last_login_ip = request.remote_addr
        db.session.commit()
        
        # 生成JWT令牌
        token_payload = {
            'admin_id': admin.id,
            'username': admin.username,
            'role': admin.role,
            'exp': datetime.utcnow() + timedelta(hours=8)
        }
        token = jwt.encode(token_payload, 'billiard-jwt-secret', algorithm='HS256')
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'data': {
                'token': token,
                'admin': admin.to_dict()
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'登录失败: {str(e)}'}), 500

@auth_bp.route('/admin/logout', methods=['POST'])
def admin_logout():
    """管理员登出"""
    return jsonify({
        'success': True,
        'message': '登出成功'
    })

@auth_bp.route('/verify', methods=['GET'])
def verify_token():
    """验证令牌"""
    try:
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'success': False, 'message': '缺少访问令牌'}), 401
        
        if token.startswith('Bearer '):
            token = token[7:]
        
        # 解析令牌
        data = jwt.decode(token, 'billiard-jwt-secret', algorithms=['HS256'])
        
        if 'user_id' in data:
            # 用户令牌
            user = User.query.get(data['user_id'])
            if not user:
                return jsonify({'success': False, 'message': '用户不存在'}), 404
            
            return jsonify({
                'success': True,
                'data': {
                    'type': 'user',
                    'user': user.to_dict()
                }
            })
        
        elif 'admin_id' in data:
            # 管理员令牌
            admin = Admin.query.get(data['admin_id'])
            if not admin:
                return jsonify({'success': False, 'message': '管理员不存在'}), 404
            
            return jsonify({
                'success': True,
                'data': {
                    'type': 'admin',
                    'admin': admin.to_dict()
                }
            })
        
        else:
            return jsonify({'success': False, 'message': '无效的令牌'}), 401
            
    except jwt.ExpiredSignatureError:
        return jsonify({'success': False, 'message': '令牌已过期'}), 401
    except jwt.InvalidTokenError:
        return jsonify({'success': False, 'message': '无效的令牌'}), 401
    except Exception as e:
        return jsonify({'success': False, 'message': f'验证失败: {str(e)}'}), 500